const { default: axios } = require("axios")
const { writeFileSync, createWriteStream, existsSync, mkdirSync, promises, statSync, rmSync } = require("fs")
const { join, resolve } = require("path")

let month = process.argv[2]

void async function main (month) {
  if (!main) {
    console.log('需要输入月份参数，如：')
    console.log('node', __filename, '2024-08')
    return
  }
  /**@type string */
  let { data: content } = await axios.get(`https://mirror.ghproxy.com/https://raw.githubusercontent.com/niumoo/bing-wallpaper/main/picture/${month}/README.md`)
  let reg = /(\d{4}-\d{2}-\d{2}) \[download 4k\]\((.+?)\)\|/g
  while (reg.test(content)) {
    let date = RegExp.$1
    let href = RegExp.$2
    let oUrl = new URL(href)
    let id = oUrl.searchParams.get('id')
    let outputDir = join(__dirname, '../img/')
    if (!existsSync(outputDir)) mkdirSync(outputDir)
    let output = join(outputDir, date + '.' + id)
    if (existsSync(output)) { continue }

    let contentLength
    axios.get(href, { responseType: 'stream' })
      .then(res => {
        contentLength = +res.headers['content-length']
        return new Promise((resolve, reject) => {
          let rs = res.data
          rs.pipe(createWriteStream(output))
          rs.on('end', resolve)
            .on('error', reject)
        })
      })
      .then(() => {
        let fInfo = statSync(output)
        if (fInfo.size !== contentLength) {
          throw new Error('文件大小不匹配，内容不完整')
        }
      })
      .catch(err => {
        if (existsSync(output)) rmSync(output)
        writeFileSync(join(__dirname, '../', 'err.log'), `${date} ${href} ${err.message}\n`, { flag: 'a' })
      })
  }
}(month)
